package com.etc.zzysys.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.zzsys.entiy.AnswerBean;
import com.etc.zzsys.service.AnswerService;
import com.etc.zzsys.service.impl.AnswerServiceImpl;
import com.etc.zzsys.util.PageData;

/**
 * Servlet implementation class QuestionServlet
 * 
 * 这个servlet处理的是所有和问题有关的请求
 */
@WebServlet("/as.action")
public class AnswerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private AnswerService as = new AnswerServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AnswerServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 处理请求编码:切记，处理请求第一件事情就是设置请求编码
		request.setCharacterEncoding("utf-8");
		// String v=request.getParameter("表单中的文本名，select名字等等/参数名"); 接收请求参数的值
		String op = request.getParameter("op");
		if ("queryans".equals(op)) {
			// 调用service的查询问题的方法...
			List<AnswerBean> list = as.getAnswers();
			// list 我们需要将集合的数据传递页面 jsp
			// 最常用的方法是使用请求对象request对象来传递数据
			// request.setAttribute("string -key" ,Object value)
			request.setAttribute("list", list);
			// 从当前控制器跳转到jsp页面[问题列表]，跳转的方法叫做转发
			request.getRequestDispatcher("answer.jsp").forward(request, response);
		}else if ("queryansByPage".equals(op)) {
			
			int page =1;//默认第一页
			int pageSize = 10;//默认每页显示10条
			//如果用户传递的参数不为空
			if(request.getParameter("page")!=null)
			{
				page = Integer.parseInt(request.getParameter("page"));
			}
			
			if(request.getParameter("pageSize")!=null)
			{
				pageSize = Integer.parseInt(request.getParameter("pageSize"));
			}
			
			//增加了模糊查询的部分;
			String keywords="";
			if(request.getParameter("keywords")!=null)
			{
				keywords = request.getParameter("keywords");
			}
			
			
			//之前的代码要变
			PageData<AnswerBean> pd=as.queryAnswersByPage(page, pageSize,keywords);
			
			 
			request.setAttribute("pd", pd);
			//需要将每次模糊查询的关键字传递回来给jsp
			request.setAttribute("keywords", keywords);
			// 从当前控制器跳转到jsp页面[问题列表]，跳转的方法叫做转发
			request.getRequestDispatcher("answer_page.jsp").forward(request, response);
			
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
